#include <cstdlib>
#include <iostream>

typedef struct
{
    char* bits;
    int numBits;
}BitString;
       
BitString* CreateBitString(int numWeights)
{
    BitString *toReturn = (BitString*)malloc(sizeof(BitString));
    toReturn->bits = (char*)malloc(sizeof(char) * numWeights);
    toReturn->numBits = numWeights;
    
    return toReturn;
}

void DestroyBitString(BitString* toDestroy)
{
    free(toDestroy->bits);
    free(toDestroy);
}

/***********************************
 * BitStringToInt
 *
 * Input: Array of BitStrings, Number of BitStrings
 * Outputs: Array of Integers(8-Bit Aligned), Number of Integers (Don't allocate space for theInts*)
 *
 */ 
void BitStringToInt(BitString* theBitString, int numBitStrings, int** theInts, int* numIntsReturned)
{
    int weights[8] = {128, 64, 32, 16, 8, 4, 2, 1};
    int i, j;
    int currentIterator = 0;
    int currentIntTotal = 0;
    int num = theBitString->numBits;
    
    *numIntsReturned = ((num * numBitStrings) / 8) + 1;
    
    if(!numBitStrings)
        *numIntsReturned = 0;
    else
        *theInts = (int*)malloc(sizeof(int) * *numIntsReturned);
    
    int* tempHead = *theInts;
    
    for(i = 0; i < numBitStrings; i++)
    {
        for(j = 0; j < num; j++)
        {
            currentIntTotal += weights[currentIterator] * (theBitString->bits[j] - 48);
            currentIterator++;
            
            if(currentIterator >= 8)
            { 
                *tempHead = currentIntTotal;
                currentIterator = 0;
                currentIntTotal = 0;
                (tempHead) += 1;
            }
        }
    }
    
    if(currentIterator != 0)
       *tempHead = currentIntTotal;
}
   
